#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time: 2019/10/14  14:01
# @Author: 余浪人
# @email: yulangren520@gmail.com
import random, base64, os
from io import BytesIO
from PIL import Image, ImageDraw, ImageFont


def getRandomColor():  # 随机颜色
    r = random.randint(0, 255)
    g = random.randint(0, 255)
    b = random.randint(0, 255)
    return (r, g, b)


def getRandomChar():
    random_num = str(random.randint(0, 9))
    random_lower = chr(random.randint(97, 122))  # 小写字母a~z
    random_upper = chr(random.randint(65, 90))  # 大写字母A~Z
    random_char = random.choice([random_num, random_lower, random_upper])
    return random_char


def drawLine(draw, width: int, height: int):  # 随机噪音线条。
    for i in range(5):
        x1 = random.randint(0, width)
        x2 = random.randint(0, width)
        y1 = random.randint(0, height)
        y2 = random.randint(0, height)
        draw.line((x1, y1, x2, y2), fill=getRandomColor())


def drawPoint(draw, width: int, height: int):  # 随机画点，随机生成横纵坐标点
    for i in range(100):
        x = random.randint(0, width)
        y = random.randint(0, height)
        draw.point((x, y), fill=getRandomColor())


def createImg(width: int, height: int):
    bg_color = getRandomColor()
    img = Image.new(mode="RGB", size=(width, height), color=bg_color)  # 创建一张随机背景色的图片
    draw = ImageDraw.Draw(img)  # 获取图片画笔，用于描绘字
    ttf_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))).replace('\\','/')+'/static/fonts/arial.ttf'
    font = ImageFont.truetype(font=ttf_path, size=34)  # 修改字体
    verifyCode = []
    for i in range(5):  # 随机生成5种字符+5种颜色
        random_txt = getRandomChar()
        verifyCode.append(random_txt)
        txt_color = getRandomColor()
        while txt_color == bg_color: txt_color = getRandomColor()  # 避免文字颜色和背景色一致重合
        draw.text((10 + 30 * i, 3), text=random_txt, fill=txt_color, font=font)  # 根据坐标填充文字
    # 加干扰线点
    drawLine(draw, width, height)
    drawPoint(draw, width, height)
    f = BytesIO()
    img.save(f, format="png")
    raw_data = f.getvalue()  # 从内存中取出bytes类型的图片
    imgData = base64.b64encode(raw_data).decode()  # 将bytes转成base64
    code = ''.join(verifyCode)
    return code, imgData


def createMain(width: int, height: int):
    '''
    生成验证码
    :param width: 宽
    :param height: 高
    :return:
    '''
    return createImg(width, height)
